package com.kx.base.util;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 异步请求的工具类
 *
 * @Author Sun
 * @Date 2021/7/22 16:22
 */
public class AsyncBatchCallUtil {
    /**
     * 线程池服务
     */
    public static ExecutorService executorService;

    static {
        //核心线程数
        int corePoolSize = 5;
        //最大线程数
        int maximumPoolSize = 10;
        //非核心线程数的最大存活时间
        long keepAliveTime = 10;
        //时间单位
        TimeUnit unit = TimeUnit.SECONDS;
        //工作队列
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(6);
        //线程工厂
        ThreadFactory threadFactory = new UserThreadFactory("kx");
        //拒绝策略
        RejectedExecutionHandler handle = new MyRejectPolicy();

        //实例化
        executorService = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handle);
    }

    /**
     * 线程工厂
     */
    static class UserThreadFactory implements ThreadFactory {

        //名字前缀
        private final String namePrefix;

        private final AtomicInteger nextId = new AtomicInteger();

        UserThreadFactory(String groupName) {
            namePrefix = "From" + this.getClass().getName() + "-" + groupName + "-";
        }

        @Override
        public Thread newThread(Runnable r) {
            //指定线程名,见明之意
            String name = namePrefix + nextId.getAndIncrement();
            Thread thread = new Thread(null, r, name);
            return thread;
        }
    }

    /**
     * 拒绝策略
     */
    static class MyRejectPolicy implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            //不指定使用默认的拒绝策略
            System.out.println(AsyncBatchCallUtil.class.getName() + "的线程队列已经满了");
        }
    }

    /**
     * 对外界提供公共的方法
     */
    public static void execute(Runnable task) {
        executorService.execute(task);
    }
}
